# load data

library(foreign)
library(readstata13)
library(plyr)
library(ggplot2)
library(grid)
library(gridExtra)



load(file="replication.rda")
#### SUPPORT FUNCTIONS ####

## Summary Function for Figures ##

summarySE <- function(data=NULL, measurevar, groupvars=NULL, na.rm=FALSE,
                      conf.interval=.95, .drop=TRUE) {
  require(plyr)
  
  # New version of length which can handle NA's: if na.rm==T, don't count them
  length2 <- function (x, na.rm=FALSE) {
    if (na.rm) sum(!is.na(x))
    else       length(x)
  }
  
  # This does the summary. For each group's data frame, return a vector with
  # N, mean, and sd
  datac <- ddply(data, groupvars, .drop=.drop,
                 .fun = function(xx, col) {
                   c(N    = length2(xx[[col]], na.rm=na.rm),
                     mean = mean   (xx[[col]], na.rm=na.rm),
                     sd   = sd     (xx[[col]], na.rm=na.rm)
                   )
                 },
                 measurevar
  )
  
  # Rename the "mean" column    
  datac <- plyr::rename(datac, c("mean" = measurevar))
  
  datac$se <- datac$sd / sqrt(datac$N)  # Calculate standard error of the mean
  
  # Confidence interval multiplier for standard error
  # Calculate t-statistic for confidence interval: 
  # e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
  ciMult <- qt(conf.interval/2 + .5, datac$N-1)
  datac$ci <- datac$se * ciMult
  
  return(datac)
}

## Legend Extract Function for Figures ##

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}


binconvert <- function(data, varnames, varlabel){
  for(i in 1:length(varnames)){
    temp.summary <- summarySE(data, measurevar=varnames[i], groupvars=c("party.f"), na.rm=TRUE)[1:2, 1:3]
    temp.summary$Source <- varlabel[i]
    names(temp.summary)[names(temp.summary)==varnames[i]] <- "groupingvariable"
    bin_add <- join(bin_add, temp.summary, type="full") 
    remove(temp.summary)
  }
  return(bin_add)
}



#### FIGURE 1. ####

#Considerations Staffers Reported as Extremely or Very Important in Shaping Ad- vice to Their Members, by Staffer Party.


influence.vector <- c("influence_gao_bin", "influence_crs_bin", "influence_consts_bin", "influence_wholecon_bin",
                      "influence_partylead_bin","influence_biz_bin","influence_unions_bin","influence_thinktank_bin",
                      "influence_primaryopp_bin","influence_reelect_bin","influence_commconst_bin")
influence.label <- c("GAO", "CRS", "Public opinion of constituents", "Public opinion of country",
                     "Party leaders","Businesses","Unions","Think tanks",
                     "Concerns about primary opponents","Concerns about re-election","Communication from constituents")

cbo_bin <- summarySE(replication, measurevar=c("influence_cbo_bin"), groupvars=c("party.f"), na.rm=TRUE)[1:2, 1:3]
cbo_bin$Source <- "CBO"
names(cbo_bin)[names(cbo_bin)=="influence_cbo_bin"] <- "groupingvariable"
bin_add <- cbo_bin

influence_summary <- binconvert(data=replication, varnames=influence.vector, varlabel=influence.label)

quartz(width=7, height=5.5)

ggplot(data=influence_summary, aes(x=reorder(Source, groupingvariable), y=groupingvariable, width=0.60))+
  geom_bar(stat="identity", position="dodge", aes(fill=party.f))+
  scale_fill_manual(values=c("#d3d3d3", "#808080"),guide = guide_legend(reverse=TRUE)) +
  theme_bw()+
  theme(panel.border = element_blank())+
  theme(legend.position="bottom")+
  theme(legend.key = element_blank())+
  theme(legend.title=element_blank())+
  xlab("") +
  ylab("% staffers reporting item as important consideration") + 
  coord_flip () + # note this means xlab and ylab are also flipped 
  scale_y_continuous(expand = c(0,0),  limits=c(0, 0.90), breaks=c(0, 0.25, 0.5, 0.75),
                     labels=c("0", "25", "50", "75"))

dev.copy2eps(file="POPFigures/Figure1.eps")
dev.copy2pdf(file="POPFigures/Figure1.pdf")


#### TABLE 2 ####

# survey$dv1  - How LIKELY are you to mention these letters to your Member?
# survey$dv2 - How SIGNIFICANT would these letters be in your advice to your Member about their position on the bill? 
# survey$dv3 - How REPRESENTATIVE do you think these letters are of your constituents’ opinions? 

c1_numletters <- summarySE(data=replication, measurevar=c("dv1"), groupvars=c("letters"), na.rm=TRUE)
c1_position <- summarySE(data=replication, measurevar=c("dv1"), groupvars=c("position"), na.rm=TRUE)
c1_wording <- summarySE(data=replication, measurevar=c("dv1"), groupvars=c("wording"), na.rm=TRUE)
c1_identity <- summarySE(data=replication, measurevar=c("dv1"), groupvars=c("identity"), na.rm=TRUE)

c2_numletters <- summarySE(data=replication, measurevar=c("dv2"), groupvars=c("letters"), na.rm=TRUE)
c2_position <- summarySE(data=replication, measurevar=c("dv2"), groupvars=c("position"), na.rm=TRUE)
c2_wording <- summarySE(data=replication, measurevar=c("dv2"), groupvars=c("wording"), na.rm=TRUE)
c2_identity <- summarySE(data=replication, measurevar=c("dv2"), groupvars=c("identity"), na.rm=TRUE)

c3_numletters <- summarySE(data=replication, measurevar=c("dv3"), groupvars=c("letters"), na.rm=TRUE)
c3_position <- summarySE(data=replication, measurevar=c("dv3"), groupvars=c("position"), na.rm=TRUE)
c3_wording <- summarySE(data=replication, measurevar=c("dv3"), groupvars=c("wording"), na.rm=TRUE)
c3_identity <- summarySE(data=replication, measurevar=c("dv3"), groupvars=c("identity"), na.rm=TRUE)


t.test(replication$dv1[which(replication$letters==2)], replication$dv1[which(replication$letters==20)])
t.test(replication$dv1[which(replication$letters==20)], replication$dv1[which(replication$letters==200)])
t.test(replication$dv2[which(replication$letters==2)], replication$dv2[which(replication$letters==20)])
t.test(replication$dv2[which(replication$letters==20)], replication$dv2[which(replication$letters==200)])
t.test(replication$dv3[which(replication$letters==2)], replication$dv3[which(replication$letters==20)])
t.test(replication$dv3[which(replication$letters==20)], replication$dv3[which(replication$letters==200)])

t.test(replication$dv1[which(replication$wording=="similar")], replication$dv1[which(replication$wording=="different")])
t.test(replication$dv2[which(replication$wording=="similar")], replication$dv2[which(replication$wording=="different")])
t.test(replication$dv3[which(replication$wording=="similar")], replication$dv3[which(replication$wording=="different")])



#### FIGURE 2 ####

bizcontact.vector <- c("bizcontact_empelect.bin","bizcontact_researchdraft.bin","bizcontact_poladvice.bin")
bizcontact.label <- c("Having their employees support member's electoral campaign", "Offering research and assistance, drafting legislation",
                      "Offering political advice, such as talking points and polling data")
empwrite_bin <- summarySE(replication, measurevar=c("bizcontact_empwrite.bin"), groupvars=c("party.f"), na.rm=TRUE)[1:2, 1:3]
empwrite_bin$Source <- "Having their employees write to office with opinions about policy"
names(empwrite_bin)[names(empwrite_bin)=="bizcontact_empwrite.bin"] <- "groupingvariable"
bin_add <- empwrite_bin

summarySE(replication, measurevar=c("bizcontact_researchdraft.bin"), groupvars=c("party.f"), na.rm=TRUE)

bizcontact_summary <- binconvert(data=replication, varnames=bizcontact.vector, varlabel=bizcontact.label)

quartz(width=7, height=5.5)

ggplot(data=bizcontact_summary, aes(x=reorder(Source, groupingvariable), y=groupingvariable, width=0.6, fill=party.f))+
  geom_bar(stat="identity", position="dodge")+
  scale_fill_manual(values=c("#d3d3d3", "#808080"),guide = guide_legend(reverse=TRUE)) +
  scale_x_discrete(labels = function(x) lapply(strwrap(x, width = 40, simplify = FALSE), paste, collapse="\n"))+
  theme_bw()+
  theme(panel.border = element_blank())+
  theme(legend.position="bottom")+
  theme(legend.key = element_blank())+
  theme(legend.title=element_blank())+
  #  labs(title = "Reporting interest groups as important or extrmeely important") +
  xlab("") +
  ylab("% staffers reporting business contact strategy as useful") + 
  coord_flip () + # note this means xlab and ylab are also flipped
  scale_y_continuous(expand = c(0,0),  limits=c(0, 0.90), breaks=c(0, 0.25, 0.5, 0.75),
                     labels=c("0", "25", "50", "75"))

dev.copy2eps(file="POPFigures/Figure2.eps")
dev.copy2pdf(file="POPFigures/Figure2.pdf")




